package ru.housewife.service.user;

import org.hibernate.Query;
import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.cache.CacheManager;
import ru.housewife.form.UserForm;
import ru.housewife.model.User;

import java.util.List;

/**
 * checks user exists
 *
 * @author Alexander Troshanin
 */
public class LogonUser implements HibernateAction<UserForm> {

    private String userName;

    private String userPass;

    private CacheManager cacheManager = CacheManager.getInstance();

    public LogonUser(String userName, String userPass) {
        this.userName = userName;
        this.userPass = userPass;
    }

    @Override
    public UserForm execute(Session session) {
        Query q = session.createQuery("select u from User u where u.userName=:userName and u.userPass=:userPass");
        q.setString("userName", userName);
        q.setString("userPass", userPass);
        List<User> lst = q.list();
        if (lst == null || lst.size() == 0) {
            return null;
        }
        return cacheManager.onUserLogon(lst.get(0));
    }
}
